Imports System
Imports System.Diagnostics
Imports NUnit.Framework
Imports ValidationFramework
Imports ValidationFramework.Reflection

Public Class MethodCacheExample
#Region "Example"

Public Class Bike
	' Methods

	' Assume for the purposes of this sample that a bike can have between 1 
	' and 2 wheels changed at a time.
	Public Sub ChangeWheels(ByVal numberOfWheels As Integer)
            ParameterValidationManager.ThrowException( _
Me, Bike.ChangeWheelsMethodHandle, numberOfWheels)
		Debug.WriteLine(numberOfWheels)
	End Sub


	' Fields
    Public Shared ReadOnly ChangeWheelsMethodHandle As RuntimeMethodHandle = _
    GetType(Bike).GetMethod("ChangeWheels").MethodHandle
End Class


    <TestFixture()> _
    Public Class ExampleUsage
        ' Methods
        <Test()> _
        Public Sub Run()
            Dim thrownOnTooFew As Boolean = False
            Dim thrownOnTooMany As Boolean = False
            Dim bike As New Bike

            ' 0 is valid numberOfWheels because there are no validation rules yet.
            bike.ChangeWheels(0)

            Dim rangeRule As New RangeRule(Of Integer)(1, 2)

            Dim numberOfWheelsParameterDescriptor As ParameterDescriptor = _
            MethodCache.GetMethod(bike.ChangeWheelsMethodHandle).Parameters.Item("numberOfWheels")
            numberOfWheelsParameterDescriptor.Rules.Add(rangeRule)

            ' 0 is an invalid numberOfWheels 
            Try
                bike.ChangeWheels(0)
            Catch exception1 As ArgumentException
                thrownOnTooFew = True
            End Try

            ' 1 and 2 are a valid numberOfWheels 
            bike.ChangeWheels(1)
            bike.ChangeWheels(2)

            ' 3 is an invalid numberOfWheels 
            Try
                bike.ChangeWheels(3)
            Catch exception2 As ArgumentException
                thrownOnTooMany = True
            End Try

            numberOfWheelsParameterDescriptor.Rules.Clear()

            ' 0 is valid numberOfWheels because the validation rule has been removed.
            bike.ChangeWheels(0)
            Assert.IsTrue(thrownOnTooMany)
            Assert.IsTrue(thrownOnTooFew)
        End Sub

    End Class



#End Region
End Class